package com.zhiyou.aifeng.smart_machine

import android.os.Build
import android.os.Bundle
import android.text.method.KeyListener
import android.text.method.MovementMethod
import com.aifeng.utils.getExtra
import com.jeremyliao.liveeventbus.LiveEventBus
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.animators.AnimationType
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.style.PictureWindowAnimationStyle
import com.zhiyou.aifeng.common.base.clear
import com.zhiyou.aifeng.common.base.gone
import com.zhiyou.aifeng.common.base.oneClick
import com.zhiyou.aifeng.common.base.visible
import com.zhiyou.aifeng.common.helper.*
import com.zhiyou.aifeng.common_ui.base.BaseActivity
import com.zhiyou.aifeng.common_ui.base.addItems
import com.zhiyou.aifeng.common_ui.base.loadImageNoTransform
import com.zhiyou.aifeng.common_ui.model.BaseUrl
import com.zhiyou.aifeng.common_ui.oss.OSSHelper
import com.zhiyou.aifeng.common_ui.utils.*
import com.zhiyou.aifeng.model.BrandData
import com.zhiyou.aifeng.utils.GlideEngine
import com.zhiyou.aifeng.utils.PictureSelectConst
import com.zhiyou.aifeng.utils.callback
import com.zhiyou.aifeng.viewmodel.MachineViewModel
import kotlinx.android.synthetic.main.activity_machine_add.*
import org.jetbrains.anko.toast
import org.json.JSONObject

class MachineAddActivity : BaseActivity() {

    private var mType: Int = 0
    private var mMode = ""

    private lateinit var mListener: KeyListener
    private lateinit var mMehod: MovementMethod
    private var mBrandImg = ""

    private var mBrandId = ""
    private var mBrandNumId = ""
    private var mBrandTypeId = ""
    private var mBrandTypeName = ""
    private var mProductionTime = ""

    private val mBrandList = ArrayList<BrandData>()
    private val mBrandNumList = ArrayList<BrandData>()
    private val mBrandTypeList = ArrayList<BrandData>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_machine_add)
        mType = intent.getIntExtra("type", 0)
        mMode = intent.getExtra("mode")
        initTitle(
            title = when (mType) {
                1 -> {
                    when (mMode) {
                        "modify" -> "修改农具"
                        else -> "添加农具"
                    }
                }
                else -> {
                    when (mMode) {
                        "modify" -> "修改农机"
                        else -> "添加农机"
                    }
                }
            }
        )

        if (mMode == "modify") getData()
    }

    override fun getViewModel() = get<MachineViewModel>()

    override fun initTitle(title: String, name: String, divider: Boolean) {
        super.initTitle(title, name, divider)
        initListener()

        when (mType) {
            1 -> {
                view4.text = "农具品牌"
                machine_brand.hint = "请选择农具品牌"
                machine_type.setLeftString("农具类型")
                machine_type.setRightHintString("请选择农具类型")
                machine_num.hint = "请选择农具型号"
                view1.text = "农具型号"
                view3.text = "上传农具照片"
                machine_extra.gone()
            }
            else -> {
                view4.text = "农机品牌"
                machine_brand.hint = "请选择农机品牌"
                machine_type.setLeftString("农机类型")
                machine_type.setRightHintString("请选择农机类型")
                machine_num.hint = "请选择农机型号"
                view1.text = "农机型号"
                view3.text = "上传农机照片"
                machine_extra.visible()
            }
        }
    }

    override fun initListener() {
        mMehod = machine_num.movementMethod
        mListener = machine_num.keyListener

        machine_num.apply {
            isFocusable = false
            isFocusableInTouchMode = false
            hint = "请选择${if (mType == 0) "农机" else "农具"}型号"
            movementMethod = null
            keyListener = null
            clear()
        }

        machine_brand.apply {
            isFocusable = false
            isFocusableInTouchMode = false
            hint = "请选择${if (mType == 0) "农机" else "农具"}品牌"
            movementMethod = null
            keyListener = null
            clear()
        }

        machine_num_ll.oneClick {
            toast("请选择${if (mType == 0) "农机" else "农具"}品牌")
        }

        machine_type.oneClick {
            getViewModel().getTypeList(
                if (mType == 0) "vehicleType"
                else "farmTools"
            )
                .bindLifeCycle(getLifecycleOwner())
                .subscribeByFinally(
                    event = getViewModel(),
                    onSuccess = { items ->
                        mBrandTypeList.clear()
                        mBrandTypeList.addItems(items)

                        if (mBrandTypeList.isNotEmpty()) {
                            showListDialog(
                                title = "请选择${if (mType == 0) "农机" else "农具"}类型",
                                index = mBrandTypeList.indexOfFirst { it.id == mBrandTypeId },
                                items = mBrandTypeList.mapTo(ArrayList()) { it.name }
                            ) { index, name ->
                                mBrandTypeId = mBrandTypeList[index].id
                                mBrandTypeName = name
                                machine_type.setRightString(mBrandTypeName)
                            }
                        }
                    }
                )
        }

        machine_brand_ll.oneClick {
            getViewModel().getBrandList(mType)
                .bindLifeCycle(getLifecycleOwner())
                .subscribeByFinally(
                    event = getViewModel(),
                    onSuccess = { items ->
                        mBrandList.clear()
                        mBrandList.addItems(items)

                        if (mBrandList.isEmpty()) {
                            mBrandId = "0"
                            setNumInput()
                            setBrandInput()
                        } else {
                            showListDialog(
                                title = "请选择${if (mType == 0) "农机" else "农具"}品牌",
                                index = mBrandList.indexOfFirst { it.id == mBrandId },
                                items = mBrandList.mapTo(ArrayList()) { it.name }
                            ) { index, name ->
                                mBrandId = mBrandList[index].id
                                machine_brand.setText(name)

                                getNumList()
                            }
                        }
                    }
                )
        }

        machine_time.oneClick {
            showTimeDialog(
                count = 3,
                title = "请选择出厂时间",
                isCurrentDate = true,
                isAfterLimited = true
            ) { _, _, _, _, _, date ->
                mProductionTime = date
                machine_time.setRightString(date)
            }
        }

        machine_hint.oneClick {
            showOneHintDialog(
                title = "提示",
                hint = getString(R.string.hint_machine_num),
                sure = "我知道了"
            )
        }

        bt_upload.oneClick { openGallery() }
        bt_sure.oneClick {
            when {
                mBrandTypeId.isEmpty() -> {
                    toast("请选择${if (mType == 0) "农机" else "农具"}类型")
                    return@oneClick
                }
                mBrandId.isEmpty() -> {
                    toast("请选择${if (mType == 0) "农机" else "农具"}品牌")
                    return@oneClick
                }
                mBrandId == "0" && machine_brand.text.isBlank() -> {
                    toast("请输入${if (mType == 0) "农机" else "农具"}品牌")
                    return@oneClick
                }
                machine_num.text.isBlank() -> {
                    if (mBrandNumList.isEmpty()) {
                        toast("请输入${if (mType == 0) "农机" else "农具"}型号")
                        machine_num.requestFocus()
                    } else {
                        toast("请选择${if (mType == 0) "农机" else "农具"}型号")
                    }
                    return@oneClick
                }
                machine_power.text.isNotEmpty() -> {
                    when {
                        machine_power.textString().toNotDouble() < 10 -> {
                            toast("农机马力应不少于10匹")
                            return@oneClick
                        }
                        machine_power.textString().toNotDouble() > 2000 -> {
                            toast("农机马力应不超过2000匹")
                            return@oneClick
                        }
                    }
                }
                mBrandImg.isEmpty() -> {
                    toast("请上传${if (mType == 0) "农机" else "农具"}照片")
                    return@oneClick
                }
            }

            getViewModel().request(
                requestUrl = BaseUrl.addBrand,
                params = *arrayOf(
                    "uid" to getString("userId"),
                    "type" to mType,
                    "id" to intent.getExtra("id"),
                    "vehicleType" to mBrandTypeId,
                    "vehicleTypeName" to mBrandTypeName,
                    "vehicleBrand" to mBrandId,
                    "vehicleBrandName" to machine_brand.trimString(),
                    "model" to mBrandNumId,
                    "vehicleModel" to machine_num.trimString(),
                    "img" to mBrandImg,
                    "engineNo" to machine_code.textString(),
                    "horsepower" to (if (machine_power.text.isEmpty()) 0 else machine_power.textString()),
                    "productionTime" to mProductionTime,
                    "plateNo" to machine_car.trimString()
                ),
                onResult = {
                    toast("添加信息已提交，请耐心等待审核！")
                    LiveEventBus.get("machineList").post("add")
                    finishView()
                }
            )
        }
    }

    private fun getNumList() {
        getViewModel().getNumList(mType, mBrandId)
            .bindLifeCycle(getLifecycleOwner())
            .subscribeByFinally(
                event = getViewModel(),
                onSuccess = { items ->
                    mBrandNumList.clear()
                    mBrandNumList.addItems(items)

                    if (mBrandNumList.isEmpty()) {
                        mBrandNumId = "0"
                        setNumInput()
                    } else {
                        setNumSelect()

                        machine_num_ll.oneClick {
                            showListDialog(
                                title = "请选择${if (mType == 0) "农机" else "农具"}型号",
                                index = mBrandNumList.indexOfFirst { it.id == mBrandNumId },
                                items = mBrandNumList.mapTo(ArrayList()) { it.name }
                            ) { index, name ->
                                mBrandNumId = mBrandNumList[index].id
                                machine_num.setText(name)
                            }
                        }
                    }
                }
            )
    }

    private fun setBrandInput() {
        machine_brand.apply {
            isFocusable = true
            isFocusableInTouchMode = true
            hint = "请输入${if (mType == 0) "农机" else "农具"}品牌"
            movementMethod = mMehod
            keyListener = mListener
            clear()
            requestFocus()
        }
        machine_brand_ll.setOnClickListener(null)
    }

    private fun setNumInput() {
        machine_num.apply {
            isFocusable = true
            isFocusableInTouchMode = true
            hint = "请输入${if (mType == 0) "农机" else "农具"}型号"
            movementMethod = mMehod
            keyListener = mListener
            clear()
            requestFocus()
        }
        machine_num_ll.setOnClickListener(null)
    }

    private fun setNumSelect() {
        machine_num.apply {
            isFocusable = false
            isFocusableInTouchMode = false
            hint = "请选择${if (mType == 0) "农机" else "农具"}型号"
            movementMethod = null
            keyListener = null
            clear()
        }
    }

    private fun openGallery() {
        PictureSelector.create(this)
            .openGallery(PictureMimeType.ofImage())
            .imageEngine(GlideEngine.createGlideEngine())
            .theme(R.style.Picture_Green_Style)
            .setPictureWindowAnimationStyle(PictureWindowAnimationStyle())
            .setRecyclerAnimationMode(AnimationType.DEFAULT_ANIMATION)
            .isMaxSelectEnabledMask(false)
            .maxSelectNum(1)
            .selectionMode(PictureConfig.SINGLE)
            .isCamera(true)
            .apply {
                if (Build.BRAND == "LeEco"
                    && Build.VERSION.SDK_INT < Build.VERSION_CODES.Q
                ) {
                    setOutputCameraPath(PictureSelectConst.getSavePath())
                }
            }
            .isGif(false)
            .isCompress(true)
            .isEnableCrop(true)
            .withAspectRatio(1, 1)
            .hideBottomControls(true)
            .circleDimmedLayer(false)
            .showCropFrame(true)
            .showCropGrid(true)
            .isOpenClickSound(false)
            .cutOutQuality(90)
            .minimumCompressSize(100)
            .callback {
                onResult {
                    val media = it[0]

                    OSSHelper.manager.uploadImage(
                        path = if (media.isCompressed) media.compressPath else media.cutPath,
                        onBefore = { showLoading("正在上传中...") },
                        onAfter = { dismissLoading() },
                        onSuccess = { result ->
                            mBrandImg = result.responseHeader["url"].orEmpty()
                            machine_img.loadImageNoTransform(
                                mBrandImg,
                                resourceId = R.mipmap.default_logo2
                            )
                        },
                        OnError = { toast("网络异常，请稍候再试！") }
                    )
                }
            }
    }

    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel().request(
            requestUrl = BaseUrl.brandDetail,
            params = *arrayOf("id" to intent.getExtra("id")),
            onResult = {
                val obj = JSONObject(it)

                mBrandId = obj.optNotNull("brand")
                mBrandTypeId = obj.optNotNull("vehicleType")
                mBrandNumId = obj.optNotNull("model")
                mBrandTypeName = obj.optNotNull("vehicleTypeName")

                if (mBrandId == "0") {
                    setNumInput()
                    setBrandInput()
                }


                val brandName = obj.optNotNull("brandName")
                val modelName = obj.optNotNull("modelName")

                machine_type.setRightString(mBrandTypeName)
                machine_brand.setText(brandName)
                machine_num.setText(modelName)

                machine_brand.setSelection(machine_brand.text.length)
                machine_num.setSelection(machine_num.text.length)

                mProductionTime = obj.optNotNull("productionTime").getTimeString("yyyy-MM-dd")
                machine_code.setText(obj.optNotNull("engineNo"))
                machine_power.setText(obj.optNotNull("horsepower"))
                machine_time.setRightString(mProductionTime)
                machine_car.setText(obj.optNotNull("plateNo"))

                mBrandImg = obj.optNotNull("img")
                machine_img.loadImageNoTransform(
                    mBrandImg,
                    resourceId = R.mipmap.default_logo2
                )
            }
        )
    }

}